package in.muton.edushare.poll.reuse;

import in.muton.edushare.components.calendar.api.UniqueElementList;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.poll.pages.PollBase;
import in.muton.edushare.poll.pages.PollEdit;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.Iterator;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.dao.PollsDAO;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.Users;

public class PollReusePanel extends EdusharePanel {
	private static final long serialVersionUID = 6914101883818368282L;
	private IModel<Poll> selectedPoll = null;
	private IModel<Poll> newPoll = null;
	private PollBase page = null;
	
	public PollReusePanel(String id, IModel<Poll> newPollModel,
			PollBase page) {
		super(id, page);
		this.page = page;
		newPoll = newPollModel;
		Form<Void> f = new Form<Void>("pollSelectionForm") {
			private static final long serialVersionUID = 1L;

			@Override
			public void onSubmit() {
				if (selectedPoll != null) {
					PollsDAO pDAO = new PollsDAO(getORMInterface());
					pDAO.copyPollQuestions(newPoll.getObject(), selectedPoll
							.getObject());
					PageParameters params = new PageParameters();
					params.put("0", newPoll.getObject().getPollId().toString());
					setResponsePage(PollEdit.class, params);
				}
			}
		};

		add(f);
		f.add(new DropDownChoice<IModel<Poll>>("pollSelection", new Model<IModel<Poll>>() {
			private static final long serialVersionUID = 2613640953254922446L;

			@Override
			public void setObject(IModel<Poll> m) {
				selectedPoll = m;
			}

			@Override
			public IModel<Poll> getObject() {
				return selectedPoll;
			}
		}, getUserPollList().getObject(), new IChoiceRenderer<IModel<Poll>>() {
			private static final long serialVersionUID = 1L;

			public Object getDisplayValue(IModel<Poll> arg0) {
				return arg0.getObject().getPollName();
			}

			public String getIdValue(IModel<Poll> arg0, int arg1) {
				return arg0.getObject().getPollId().toString();
			}
		}));
	}

	public IModel<Poll> getChosenPoll() {
		return selectedPoll;
	}

	private CayenneList<Poll> getUserPollList() {
		Users user = getLoggedInUser();
		PollsDAO upDAO = new PollsDAO(getORMInterface());
		UniqueElementList<Poll> pL = new UniqueElementList<Poll>(upDAO
				.getPollsByCreator(user));
		pL.add(upDAO.getPollsByUser(user));
		Iterator<IModel<Poll>> it = pL.getObject().iterator();
		while(it.hasNext()){
			IModel<Poll> p = it.next();
			if(p.getObject() == page.getPollModel().getObject())
				it.remove();
		}
		return pL;
	}
}
